package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.handler.CanalAvailableJobHandler;
import com.innovation.ic.b1b.monitor.base.mapper.CanalAvailableJobMapper;
import com.innovation.ic.b1b.monitor.base.model.Canal;
import com.innovation.ic.b1b.monitor.base.model.CanalAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.constant.CanalAvailableJobConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.enums.EnableEnum;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.canalAvailableJob.CanalAvailableJobInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.pojo.variable.canalAvailableJob.CanalAvailableJobListRespData;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.CanalAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.canalAvailableJob.CanalAvailableJobAddVo;
import com.innovation.ic.b1b.monitor.base.vo.canalAvailableJob.CanalAvailableJobListQueryVo;
import com.innovation.ic.b1b.monitor.base.vo.canalAvailableJob.CanalAvailableJobUpdateVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @desc   Canal可用任务表Service实现类
 * @author linuo
 * @time   2023年5月12日10:01:55
 */
@Slf4j
@Service
public class CanalAvailableJobServiceImpl extends ServiceImpl<CanalAvailableJobMapper, CanalAvailableJob> implements CanalAvailableJobService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 添加canal监控任务
     * @param canalAvailableJobAddVo 添加canal监控任务的Vo类
     * @return 返回添加结果
     */
    @Override
    public ServiceResult<Boolean> add(CanalAvailableJobAddVo canalAvailableJobAddVo) {
        boolean result = Boolean.FALSE;
        String message;

        Boolean aBoolean = judgeIfHaveSameData(null, canalAvailableJobAddVo.getCanalId());
        if(aBoolean){
            message = "当前canal监控任务已存在，请勿重复添加";
        }else{
            // 校验canalId是否存在
            Canal canal = serviceHelper.getCanalMapper().selectById(canalAvailableJobAddVo.getCanalId());
            if(canal != null){
                CanalAvailableJob canalAvailableJob = new CanalAvailableJob();
                BeanUtils.copyProperties(canalAvailableJobAddVo, canalAvailableJob);
                if(canalAvailableJob.getEnable() == null){
                    canalAvailableJob.setEnable(EnableEnum.NO.getCode());
                }
                canalAvailableJob.setCreateTime(new Date(System.currentTimeMillis()));
                int insert = serviceHelper.getCanalAvailableJobMapper().insert(canalAvailableJob);
                if(insert > 0){
                    message = ServiceResult.INSERT_SUCCESS;
                    result = Boolean.TRUE;

                    String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + canalAvailableJob.getId();

                    // 组装任务参数
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put(JobDataMapConstant.ID, canalAvailableJob.getId());

                    serviceHelper.getQuartzManager().createScheduleJob(jobId, CanalAvailableJobHandler.class.getName(), "CanalAvailableJobHandler", jobDataMap, canalAvailableJob.getScheduleExpression());
                }else{
                    message = ServiceResult.INSERT_FAIL;
                }
            }else{
                message = "canal信息不存在，请配置canal信息后重新添加canal监控任务";
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 查询canal监控任务列表
     * @param canalAvailableJobListQueryVo 查询canal监控任务列表的Vo类
     * @param isMain 是否查询主库
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<PageInfo<CanalAvailableJobListRespData>> queryList(CanalAvailableJobListQueryVo canalAvailableJobListQueryVo, Boolean isMain) {
        PageHelper.startPage(canalAvailableJobListQueryVo.getPageNo(), canalAvailableJobListQueryVo.getPageSize());

        // 查询canal可用任务列表数据
        List<CanalAvailableJobListRespData> data = serviceHelper.getCanalAvailableJobMapper().queryList(canalAvailableJobListQueryVo);
        PageInfo<CanalAvailableJobListRespData> pageInfo = new PageInfo<>(data);

        return ServiceResult.ok(pageInfo, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 删除canal监控任务
     * @param id 主键id
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delete(Integer id) {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.DELETE_FAIL;

        int i = serviceHelper.getCanalAvailableJobMapper().deleteById(id);
        if(i > 0){
            logger.info("已删除id为[{}]canal监控任务", id);
            result = Boolean.TRUE;
            message = ServiceResult.DELETE_SUCCESS;

            try {
                // 删除任务
                String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + id;
                serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            }catch (Exception e){
                logger.info("删除canal监控后台任务失败,原因:", e);
            }
        }else{
            logger.info("删除id为[{}]canal监控任务失败，数据不存在", id);
        }

        return ServiceResult.ok(result, message);
    }

    /**
     * 获取canal监控任务详情
     * @param id 主键id
     * @param isMain 是否查询主库
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<CanalAvailableJobInfoRespPojo> info(Integer id, Boolean isMain) {
        CanalAvailableJobInfoRespPojo result = serviceHelper.getCanalAvailableJobMapper().info(id);
        return ServiceResult.ok(result, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 更新canal监控任务
     * @param canalAvailableJobUpdateVo 更新canal监控任务的Vo类
     * @return 返回更新结果
     */
    @Override
    public ServiceResult<Boolean> update(CanalAvailableJobUpdateVo canalAvailableJobUpdateVo) {
        Boolean aBoolean = judgeIfHaveSameData(canalAvailableJobUpdateVo.getId(), canalAvailableJobUpdateVo.getCanalId());
        if(aBoolean){
            ServiceResult<Boolean> serviceResult = new ServiceResult<>();
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(Boolean.FALSE);
            serviceResult.setMessage("当前canal监控任务已存在，请勿重复添加");
            return serviceResult;
        }else{
            // 校验canalId是否存在
            Canal canal = serviceHelper.getCanalMapper().selectById(canalAvailableJobUpdateVo.getCanalId());
            if(canal != null){
                CanalAvailableJob historyData = serviceHelper.getCanalAvailableJobMapper().selectById(canalAvailableJobUpdateVo.getId());

                int i = serviceHelper.getCanalAvailableJobMapper().updateInfo(canalAvailableJobUpdateVo);
                if(i > 0){
                    logger.info("更新id为[{}]canal监控任务成功", canalAvailableJobUpdateVo.getId());

                    Integer enable = canalAvailableJobUpdateVo.getEnable();
                    // 原来是启用现在关闭时需要暂停后台任务
                    if(historyData.getEnable().intValue() == EnableEnum.YES.getCode().intValue() && enable.intValue() == EnableEnum.NO.getCode().intValue()){
                        String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + canalAvailableJobUpdateVo.getId();
                        logger.info("暂停后台任务,jobId:[{}]", jobId);
                        serviceHelper.getQuartzManager().pauseScheduleJob(jobId);
                    }else if(historyData.getEnable().intValue() == EnableEnum.NO.getCode().intValue() && enable.intValue() == EnableEnum.YES.getCode().intValue()) {
                        // 原来是关闭现在启用任务时需要恢复后台任务
                        String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + canalAvailableJobUpdateVo.getId();
                        logger.info("恢复后台任务,jobId:[{}]", jobId);
                        serviceHelper.getQuartzManager().resumeScheduleJob(jobId);
                    }else{
                        String scheduleExpression = canalAvailableJobUpdateVo.getScheduleExpression();
                        if(canalAvailableJobUpdateVo.getEnable().intValue() == EnableEnum.YES.getCode().intValue() && !historyData.getScheduleExpression().equals(scheduleExpression)){
                            String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + canalAvailableJobUpdateVo.getId();
                            serviceHelper.getQuartzManager().updateScheduleJob(jobId, scheduleExpression);
                        }
                    }

                    return ServiceResult.ok(Boolean.TRUE, ServiceResult.UPDATE_SUCCESS);
                }else{
                    logger.info("更新id为[{}]canal监控任务失败", canalAvailableJobUpdateVo.getId());
                    return ServiceResult.ok(Boolean.FALSE, ServiceResult.UPDATE_FAIL);
                }
            }else{
                logger.info("canalId=[{}]的信息不存在", canalAvailableJobUpdateVo.getCanalId());
                return ServiceResult.error(ServiceResult.UPDATE_FAIL);
            }
        }
    }

    /**
     * 执行任务
     * @param id 主键id
     * @return 返回执行结果
     */
    @Override
    public ServiceResult<Boolean> executeJob(Integer id) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        try {
            String jobId = TableNameConstant.CANAL_AVAILABLE_JOB + "_" + id;
            serviceHelper.getQuartzManager().runOnce(jobId);
        }catch (Exception e){
            serviceResult.setMessage(ServiceResult.OPERATE_FAIL);
            serviceResult.setResult(Boolean.FALSE);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }

        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 判断是否有相同数据
     * @param id 主键id
     * @param canalId canalId
     * @return 返回判断结果
     */
    private Boolean judgeIfHaveSameData(Integer id, Integer canalId){
        Boolean result = Boolean.FALSE;

        QueryWrapper<CanalAvailableJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CanalAvailableJobConstant.CANAL_ID, canalId);
        if(id != null){
            queryWrapper.ne(CanalAvailableJobConstant.ID, id);
        }
        Integer selectCount = serviceHelper.getCanalAvailableJobMapper().selectCount(queryWrapper);
        if(selectCount > 0){
            result = Boolean.TRUE;
        }

        return result;
    }
}